﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Topro.Application.Impl
{
    using Dapper;
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Enum;
    using Topro.Entity.Request.Login;
    using Topro.Entity.Response.Login;
    using Topro.Entity.Response.Menu;
    using Topro.Entity.Tables;
    using Topro.Log;
    using Topro.Util;

    /// <summary>
    /// 登录接口实现
    /// </summary>
    public class LoginServiceImpl :LoginService
    {
        #region 注入
        /// <summary>
        /// dapperClient
        /// </summary>
        //private readonly DapperClient _dapperClient;

        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public LoginServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public UserResponse Get(int id)
        {
            var users = _db.DbConnection.Query<UserResponse>("select * from user where Id=@Id", new { Id = id });

            var user = users.FirstOrDefault();
            if (user != null)
            {
                return user;
            }

            return null;
        }

        
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public UserResponse GetByAccount(string account)
        {
            var users = _db.DbConnection.Query<UserResponse>("select * from user where Account=@Account", new { Account = account });

            var user = users.FirstOrDefault();
            if (user != null)
            {
                return user;
            }

            return null;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult<LoginResponse> Login(LoginRequest request)
        {
            var response = new JResult<LoginResponse>()
            {
                Success = false
            };

            try
            {

                var user = _db.DbConnection.Query<UserResponse>("select * from user where Account=@Account", new { Account = request.Account }).FirstOrDefault();

                #region 验证
                if (user == null)
                {
                    throw new Exception("用户不存在！");
                }

                if (string.IsNullOrEmpty(request.Account))
                {
                    throw new Exception("用户名不能为空！");
                }

                if (string.IsNullOrEmpty(request.Password))
                {
                    throw new Exception("密码不能为空！");
                }

                var pass = EncryptionUtil.EncryptWithMd5(request.Password);

                if (user.PassWord != EncryptionUtil.EncryptWithMd5(request.Password))
                {
                    throw new Exception("密码错误！");
                }

                if (user.Status != UserStatus.启用.GetHashCode())
                {
                    throw new Exception("该用户已被管理员禁用,要继续登录请联系管理员！");
                }
                #endregion

                var loginResponse = new LoginResponse()
                {
                    UserId = user.Id,
                    UserName = user.Account,
                };

                //查询用户权限
                var querySql = $"SELECT a.* FROM role r INNER JOIN userrole ur on r.Id=ur.RoleId INNER JOIN auth a on ur.RoleId=a.RoleId WHERE r.Status=@Status AND ur.UserId=@UserId AND a.ResourceType=@ResourceType";

                var auths = _db.DbConnection.Query<Auth>(querySql, new
                {
                    Status = (int)UserStatus.启用,
                    UserId = user.Id,
                    ResourceType = (int)ResourceType.权限
                });

                if (auths!=null && auths.Any())
                {
                    //去重
                    var ids = auths.Select(c => c.ResourceId).Distinct().ToList();
                    if (ids != null && ids.Any())
                    {
                        //sql
                        var permissionSql = $"Select* From permission Where Id in({string.Join(",", ids)})";
                        //获取权限
                        var permissions = _db.DbConnection.Query<Permission>(permissionSql);
                        var codes = new List<string>();
                        //if (user.Id.Equals(1))
                        //{
                        //    codes.Add("EC");
                        //} 
                        codes = permissions.Where(c => c.Status == (int)PermissionStatus.启用).Select(c => c.Code).ToList();

                        loginResponse.UserPermissions = codes;
                    }
                }

                //日志
                _loggerService.Add(new OperLog()
                {
                    Level = 1,
                    Source = 1,
                    Message = "登录成功",
                    Exception = "",
                    Ip = "",
                    CreatedBy = 1
                });
                response.Data = loginResponse;
                response.Success = true;
                response.Message = "登录成功!";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 获取用户的菜单
        /// </summary>
        /// <param name="userId">用户编号</param>
        public List<MenuResponse> GetMenus(int userId)
        {
            //查询用户权限
            var authSql = $"SELECT a.* FROM role r INNER JOIN userrole ur on r.Id=ur.RoleId INNER JOIN auth a on ur.RoleId=a.RoleId WHERE r.Status=@Status AND ur.UserId=@UserId AND a.ResourceType=@ResourceType";

            var auths = _db.DbConnection.Query<Auth>(authSql, new
            {
                Status = (int)UserStatus.启用,
                UserId = userId,
                ResourceType = (int)ResourceType.菜单
            });

            if (auths.Any())
            {
                var ids = auths.Select(p => p.ResourceId).Distinct().ToList();
                //sql
                var menuQurySql = $"Select* From menu Where Id in({string.Join(",", ids)})";
                //获取菜单
                var menus = _db.DbConnection.Query<MenuResponse>(menuQurySql);

                return menus.ToList();
            }
            return null;
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns></returns>
        public UserAuthResponse GetAuth(int id)
        {
            var response = new UserAuthResponse();

            var user = _db.DbConnection.QueryFirst<UserResponse>("select * from user where Id=@Id", new { Id = id });
            if (user != null)
            {
                response.UserId = user.Id;
                response.Account = user.Account;
            }
            //查询用户权限
            var authSql = $"SELECT a.* FROM role r INNER JOIN userrole ur on r.Id=ur.RoleId INNER JOIN auth a on ur.RoleId=a.RoleId WHERE r.Status=@Status AND ur.UserId=@UserId AND a.ResourceType=@ResourceType";

            var auths = _db.DbConnection.Query<Auth>(authSql, new
            {
                Status = (sbyte)UserStatus.启用,
                UserId = id,
                ResourceType = (int)ResourceType.权限
            });


            if (auths.Any())
            {
                //去重
                var ids = auths.Select(c => c.ResourceId).Distinct().ToList();
                if (ids != null && ids.Any())
                {
                    //sql
                    var permissionSql = $"Select* From permission Where Id in({string.Join(",", ids)})";
                    //获取权限
                    var permissions = _db.DbConnection.Query<Permission>(permissionSql);

                    var codes = new List<string>();

                    response.UserPermissions = permissions.Where(c => c.Status == (int)PermissionStatus.启用).Select(c => c.Code).ToList();
                }
            }

            return response;
        }
    }
}
